package cn.openea.perpartner.cms.web.controller;

import cn.openea.perpartner.cms.factory.UserContext;
import cn.openea.perpartner.cms.web.entity.SysRole;
import cn.openea.perpartner.cms.web.service.ISysRoleService;
import cn.openea.perpartner.common.core.constant.UserConstants;
import cn.openea.perpartner.common.core.web.controller.BaseController;
import cn.openea.perpartner.common.core.web.domain.AjaxResult;
import cn.openea.perpartner.common.core.web.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Weird077
 * @description TODO
 * @date 2022-08-26 15:25
 */
@Api(tags = "角色管理")
@Controller
@RequestMapping("/system/role")
public class SysRoleController extends BaseController {
    @Autowired
    private ISysRoleService roleService;

    private String prefix = "system/role";

    @GetMapping()
    public String role()
    {
        return prefix + "/role";
    }

    @ApiOperation("角色列表")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysRole role)
    {
        startPage();
        List<SysRole> list = roleService.selectRoleList(role);
        return getDataTable(list);
    }
    /**
     * 新增角色
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    @ApiOperation("添加角色")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult add(@Validated SysRole role)
    {
        if (UserConstants.ROLE_NAME_NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
        {
            return error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (UserConstants.ROLE_KEY_NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
        {
            return error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateUser(UserContext.getUserId());
        role.setUpdateUser(UserContext.getUserId());
        return toAjax(roleService.save(role));

    }
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysRole role)
    {
        if (UserConstants.ROLE_NAME_NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
        {
            return error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (UserConstants.ROLE_KEY_NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
        {
            return error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateUser(UserContext.getUserId());
        return toAjax(roleService.saveOrUpdate(role));
    }

    @ApiOperation("删除角色")
    @DeleteMapping("/delete")
    @ResponseBody
    public AjaxResult delete(@RequestBody List<Long> idList) {
        return success();
    }
}
